import { fileURLToPath, URL } from "node:url";
import path, { resolve } from "path";
import { ConfigEnv, defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { log } from "node:console";

const envDir = "./";

export default defineConfig((config: ConfigEnv) => {
  // config => { mode: "development", command: "serve" , isSsrBuild:false , isPreview:false}

  const env = loadEnv(config.mode, envDir);
  //env => {VITE_PORT: '3002',VITE_PUBLIC_PATH: '/admin',VITE_SERVER_URL: 'http://192.168.2.202:3000'}

  return {
    base: env.VITE_PUBLIC_PATH,
    plugins: [vue()],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${resolve(
              "src/theme/index.less"
            )}";`,
          },
          javascriptEnabled: true,
        },
      },
    },
    server: {
      host: "0.0.0.0", //监听所有ip
      port: env.VITE_PORT as unknown as number,
      open: JSON.parse(env.VITE_OPEN), //自动打开浏览器
      hmr: true,
      proxy: {
        "/api": {
          target: env.VITE_SERVER_URL,
          changeOrigin: true,
          rewrite: (path) => {
            console.log(path)
            return path.replace(/^\/api/, "")
          } 
        },
        "/uploads": {
          target: env.VITE_SERVER_URL,
          changeOrigin: true,
          rewrite: (path) => {
            console.log(path)
            return path.replace(/^\/uploads/, "")
          } 
        },
      },
    },
    envDir,
  };
});
